package com.xingxing.Util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.xingxing.Bean.LoginBean;
import com.xingxing.Bean.User;
import com.xingxing.Interface.OkSuccessInterface;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class CommonUtils {
    private static Application context = new Application();//上下文

    /**
     * 获取上下文
     */
    public static void init(Application application) {
        context = application;
    }

    //流转换为String
    private String read(InputStream in) {
        BufferedReader reader = null;
        StringBuilder sb = null;
        String line = null;
        try {
            sb = new StringBuilder();//实例化一个StringBuilder对象
            //用InputStreamReader把in这个字节流转换成字符流BufferedReader
            reader = new BufferedReader(new InputStreamReader(in));
            //判断从reader中读取的行内容是否为空
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                if (in != null) in.close();
                if (reader != null) reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    //给ImageView控件设置网络图片
    public static void setImageByUrl(ImageView imageView, String url) {
        Handler imageHandler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    Bitmap bm = (android.graphics.Bitmap) msg.obj;
                    imageView.setImageBitmap(bm);
                } else if (msg.what == 0) {
                    Log.i("Error", "can't get the image resources!");
                }
            }
        };
        new Thread() {
            private HttpURLConnection conn;
            private Bitmap bitmap;

            @Override
            public void run() {
                try {
                    URL urls = new URL(url);
                    conn = (HttpURLConnection) urls.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        bitmap = BitmapFactory.decodeStream(is);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = bitmap;
                        imageHandler.sendMessage(msg);
                    } else {
                        Message msg = new Message();
                        msg.what = 0;
                        imageHandler.sendMessage(msg);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * OKhttp封装(json参数传递方式)无加载动画
     */
    public static void OKJsonPost(Activity activity, String json, String url, OkSuccessInterface successInterface) {
        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                .build();
        //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);

        //创建一个请求对象
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @SuppressLint("CheckResult")
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                assert activity != null;
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity.getApplicationContext(), "服务器无响应", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (successInterface != null) {
                    String json = Objects.requireNonNull(response.body()).string();
                    assert activity != null;
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            successInterface.OnSuccess(json);
                        }
                    });
                }
            }
        });
    }

    /**
     * 存储信息
     *
     * @param Mode Mode
     * @param key  键值
     * @param text 存储的内容
     */
    public static void SaveKey(String Mode, String key, String text) {
        SharedPreferences preferences = context.getSharedPreferences(Mode, Context.MODE_PRIVATE);
        preferences.edit().putString(key, text).apply();
    }

    /**
     * 获取存储信息
     *
     * @param Mode Mode
     * @param key  键值
     */
    public static String ShareKey(String Mode, String key) {
        SharedPreferences preferences = context.getSharedPreferences(Mode, Context.MODE_PRIVATE);
        String text = preferences.getString(key, null);
        return text;
    }

    public static User GetUserInfo() {
        String userinfo = ShareKey("UserInfo", "info");
        if (userinfo != null) {
            LoginBean loginBean = new Gson().fromJson(userinfo, LoginBean.class);
            return loginBean.getUser();
        } else {
            return null;
        }
    }
}

